#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int fd = open("book.dat", O_RDWR | O_CREAT, 0644);
    struct flock lock = {F_RDLCK, SEEK_SET, 0, 50, getpid()};

    if (fd == -1)
    {
        perror("open");
        exit(1);
    }

    // 检查锁状态
    if (fcntl(fd, F_GETLK, &lock) == -1)
    {
        perror("fcntl error");
        exit(1);
    }
    if (lock.l_type == F_WRLCK)
    {
        printf("File is write-locked by PID %d\n", lock.l_pid);
        exit(1);
    }
    printf("Read lock acquired. Press Enter to exit...\n");
    getchar();
    return 0;
}